package com.demo2do.wechatmcs.web.controller.wechat;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.demo2do.core.entity.result.HttpResult;
import com.demo2do.core.utils.StringUtils;
import com.demo2do.wechatmcs.entity.webauth.WebAuth;
import com.demo2do.wechatmcs.entity.webauth.WebAuthClient;
import com.demo2do.wechatmcs.entity.webauth.WebAuthConfig;
import com.demo2do.wechatmcs.handle.WebAuthHandler;
import com.demo2do.wechatmcs.service.WebAuthService;
import com.fasterxml.jackson.annotation.JsonView;

/**
 * 
 * @author mohanlan
 *
 */
@Controller()
@RequestMapping("/wechat/web-auth")
public class WebAuthController {
    
    private static final Logger logger = LoggerFactory.getLogger(WebAuthController.class);
    
    @Autowired
    private WebAuthHandler webAuthHandler;
    
    @Autowired
    private WebAuthService webAuthService;
    
    /**
     * 
     * @param webAuth
     * @return
     */
    @RequestMapping(value = "/prepare", method = RequestMethod.GET)
    public String prepare(WebAuth webAuth) {
        
        logger.info("#prepare get web auth request with params client[{}], redirect_url[{}], scope[{}], requestNo[{}]", webAuth.getClient(), webAuth.getRedirectUrl(), webAuth.getScope(), webAuth.getRequestNo());
        
        // 1. get web_auth_client according to the client host
        WebAuthClient authClient = webAuthService.getWebAuthClient(webAuth.getClient());
        
        // 2. validate web_auth from web_auth_client
        boolean success = webAuthHandler.validate(webAuth, authClient);
        
        if(success) {
            
            // 3. construct web_auth_config
            WebAuthConfig config = new WebAuthConfig(authClient);
            
            // 4. generate redirect url
            String url = webAuthHandler.prepare(webAuth, config);
            
            logger.info("#prepare - webauth finishes, redirect to url [{}]", url);
            
            return StringUtils.connect("redirect:", url);
            
        }
        
        return "/web-auth/error";
        
    }
    
    /**
     * 
     * @param uuid
     * @return
     */
    @JsonView
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public HttpResult getWebAuth(@RequestParam("uuid") String uuid) {
        
        logger.info("#getWebAuth() - start get web_auth result with uuid[{}]", uuid);
        
        HttpResult httpResult = new HttpResult();
        
        // load web_auth_response, include user_info if scope is USERINFO
        WebAuth webAuth = webAuthService.loadWebAuth(uuid);
        
        if(webAuth.isValid()) {  // valid response
            
            return httpResult.success()
                             .data("web_auth", webAuth);
            
        }
        
        return httpResult.fail("500").message("INVALID_AUTH_REQUEST");
        
    }
    
}
